package com.wyl.learn03;

import cn.hutool.core.date.StopWatch;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.wyl.config.RabbitMqConfig;

/**
 * 发布确认，多条消息批量同步发布确认
 */
public class Producer03_2 {
    public static final String TASK_QUEUE_NAME_CONFORM = "ack_queue_confirm";

    public static void main(String[] argv) throws Exception {
        //创建一个连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(RabbitMqConfig.IP);
        factory.setUsername(RabbitMqConfig.USERNAME);
        factory.setPassword(RabbitMqConfig.PASSWORD);
        //channel 实现了自动 close 接口 自动关闭 不需要显示关闭
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            // 声明非持久化队列
            channel.queueDeclare(TASK_QUEUE_NAME_CONFORM, false, false, false, null);
            // 开启发布确认
            channel.confirmSelect();
            // 一次批量确认10条消息是否发送完成
            int batchSize = 10;
            // 总共要发送的消息总数
            int MESSAGE_COUNT = 102;

            int outstandingMessageCount = 0;
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            for (int i = 0; i < MESSAGE_COUNT; i++) {
                String message = i + "";
                channel.basicPublish("", TASK_QUEUE_NAME_CONFORM, null, message.getBytes());
                outstandingMessageCount++;
                if (outstandingMessageCount == batchSize) {
                    channel.waitForConfirms();
                    outstandingMessageCount = 0;
                }
            }
            // 为了确保还有剩余没有确认消息 再次确认
            if (outstandingMessageCount > 0) {
                channel.waitForConfirms();
            }
            System.out.println("发布" + MESSAGE_COUNT + "个批量确认消息,耗时" + stopWatch.getTotalTimeMillis() + "ms");
        }
    }
}